package com.ouroboroswiki.core.xml;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;

public class SimpleNamespaceContext implements NamespaceContext {
	
	private Map<String, String> prefixesToNamespaceURIs;
	
	public SimpleNamespaceContext( Map<String, String> prefixesToNamespaceURIs ) {
		this.prefixesToNamespaceURIs = prefixesToNamespaceURIs;
	}

	@Override
	public String getNamespaceURI(String prefix) {
		String uri = prefixesToNamespaceURIs.get(prefix);
		if( uri == null ) {
			uri = XMLConstants.NULL_NS_URI;
		}
		return uri;
	}

	@Override
	public String getPrefix(String ns) {
		@SuppressWarnings("unchecked")
		Iterator<String> prefixes = getPrefixes(ns);
		if( prefixes.hasNext() ) {
			return prefixes.next();
		} else {
			return null;
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Iterator getPrefixes(String ns) {
		LinkedList<String> keys = new LinkedList<String>();
		for( Map.Entry<String, String> entry : this.prefixesToNamespaceURIs.entrySet() ) {
			if( entry.getValue().equals(ns) ) {				
				keys.add( entry.getKey() );
			}
		}
		return keys.iterator();
	}
}
